<?php
class weebUIMovieListFunctions
{
    /**
     * Returns a movie list URL
     *
     * @param array $add array of vars to add
     * @param array $replace associative array of vars to replace, with the var
     *                       to replace as the key, and its value as the value
     * @param array $remove array of vars to replace
     * @return string
     */
    public static function movieListURL( $add = false, $replace = false, $remove = false )
    {
        $urlParameters = array();
        foreach ( explode( '&', $_SERVER['QUERY_STRING'] ) as $parameterPair )
        {
            list( $name, $value ) = explode( '=', $parameterPair );
            $urlParameters[$name] = urldecode( $value );
        }

        if ( is_array( $remove ) )
        {
            foreach ( $remove as $removeVar )
            {
                if ( isset( $urlParameters[$removeVar] ) )
                    unset( $urlParameters[$removeVar] );
            }
        }

        if ( is_array( $replace ) )
        {
            foreach ( $replace as $replaceVarName => $replaceVarValue )
            {
                $urlParameters[$replaceVarName] = $replaceVarValue;
            }
        }

        if ( is_array( $add ) )
        {
            foreach ( $add as $addVarName => $addVarValue )
            {
                $urlParameters[$addVarName] = $addVarValue;
            }
        }

        foreach ( $urlParameters as $var => $value )
        {
            $parameters[] = $var . '=' . urlencode( $value );
        }
        $url = $_SERVER['PHP_SELF'] . '?';
        $url .= implode( '&', $parameters );

        return $url;
    }

    /**
    * Formats a number of minutes to hours:minutes
    * @param int $minutes
    * @return string formatted time
    **/
    public static function formatRuntime( $minutes )
    {
        $minutes = intval( $minutes );
        $hours = 0;
        if ( $minutes > 60 )
        {
            $hours = floor( $minutes / 60 );
            $minutes -= ( floor( $minutes / 60 ) * 60 );
        }
        return sprintf('%dh%02d', $hours, $minutes );
    }

    /**
     * Generates the page navigator HTML for movies
     *
     * @param int $currentPage
     * @param int $pagesCount
     * @return string
     */
    public static function moviesPageNavigatorHTML( $currentPage, $pagesCount )
    {
        $pagesCount = ceil( $pagesCount );
        if ( $pagesCount > 1 )
        {
            echo "<br><center>";
            if ( $currentPage > 1 )
                echo "<a href=\"" . weebUIMovieListFunctions::movieListURL( array( 'page' => $currentPage - 1 ) ) . "#movies-list\">";
            echo "&lt;&lt;Previous";
            if ( $currentPage > 1 )
                echo "</a>";
            echo "&nbsp;";
            for ( $i = 1; $i <= $pagesCount; $i++ )
            {
                echo "&nbsp;";
                if ( $i != $currentPage )
                    echo "<a href=\"".weebUIMovieListFunctions::movieListURL( array( 'page' => $i ) )."#movies-list\">";
                else
                    echo "<b>";
                echo $i;
                if ( $i != $currentPage )
                    echo "</a>";
                else
                    echo "</b>";
            }
            echo "&nbsp;";
            if ( $currentPage < $pagesCount )
                echo "<a href=\"".weebUIMovieListFunctions::movieListURL( array( 'page' => $currentPage + 1 ) )."#movies-list\">";
            echo "Next&gt;&gt;";
            if ( $currentPage < $pagesCount )
                echo "</a>";
            echo "</center>";
        }
    }

    /**
    * Executes an update query on a library
    * @param int $libraryID
    * @param string $query
    * @throws weebUILibraryNotFoundException if library is not found
    * @throws weebUISQLUpdateErrorException if update failed
    **/
    public static function runUpdateLibraryQuery( $libraryID, $query )
    {
        global $config, $gen;

        // open request library
        if ( !$libraryRes = sqlite_query( $config, "SELECT * FROM library WHERE id='$libraryID'" ) )
        {
            throw new weebUILibraryNotFoundException( $libraryID );
        }
        if ( sqlite_num_rows( $libraryRes ) != 1 )
        {
            throw new weebUILibraryNotFoundException( $libraryID );
        }
        $lib = sqlite_fetch_array( $libraryRes );

        $db = sqlite_open( $gen['path'] . "\\library\\" . $lib['file'] );

        $create_trigger =     "create trigger item_dates_update after update on items
                        begin
                            update item_dates set modified = idt_now()
                                where item_id = '$id';
                            update parameters set param_value = param_value + 1
                                where param_name = \"data-version\";
                        end";

        $drop = sqlite_query( $db, "drop trigger item_dates_update");

        sqlite_query( $db, $query, SQLITE_ASSOC, $errorMessage );
        if ( $errorMessage )
        {
            throw new weebUISQLUpdateErrorException( $errorMessage );
        }

        $create = sqlite_query( $db, $create_trigger );
    }

    /**
    * Returns a library DB handle based on a library ID
    * @param int $libraryID
    * @return sqliteResource
    * @todo Add exceptions
    **/
    public static function getLibraryHandle( $libraryID )
    {
        static $handles = array();
        global $config;

        if ( !isset( $handles[$libraryID] ) )
        {
            $lib = sqlite_fetch_array( sqlite_query( $config, "SELECT * FROM library WHERE id='$libraryID'" ) );
            $handles[$libraryID] = sqlite_open($gen['path'] . "\\library\\". $lib['file']);
        }

        return $handles[$libraryID];
    }

    /**
    * Returns a library based on its ID. Can also return a specific field
    * @param int $libraryID
    * @param string $field an field to return instead of the whole library data
    * @return mixed string if $field is specified, array with all info otherwise
    * @todo test if the field is set
    * @todo add erro checking on SQLLite part
    * @todo refactor using weebUILibrary
    **/
    public static function getLibrary( $libraryID, $field = false )
    {
        static $names = array();

        if ( !isset( $names[$libraryID] ) )
        {
            global $config;
            $lib = sqlite_fetch_array( sqlite_query( $config, "SELECT * FROM library WHERE id='$libraryID'" ) );
            $names[$libraryID] = $lib;
        }

        if ( !$field )
            return $names[$libraryID];
        else
            return $names[$libraryID][$field];
    }

    public static function getLibraryTags( $libraryID )
    {

    }

    /**
    * Formats a size in bytes to a human readable size with suffix
    * @param int $bytes
    * @param int $round rounding level
    * @return string the formatted filesize
    **/
    public static function formatBytes( $bytes, $round = 2 )
    {
        $suffixes = array( '', 'K', 'M', 'G', 'T', 'P' );
        $suffix = '';
        while ( $bytes > 1024 )
        {
            $bytes /= 1024;
            $suffix = next( $suffixes );
        }
        return round( $bytes, $round ) . $suffix;
    }
}

class weebUILibraryNotFoundException extends Exception
{
    function __construct( $libraryID )
    {
        $this->message = "Unknown library #{$libraryID}";
    }
}

class weebUISQLUpdateErrorException extends Exception
{
    function __construct( $SQLErrorMessage )
    {
        $this->message = "An error occured running update SQL: '{$SQLErrorMessage}'";
    }
}
?>